#include "config.h"

#include <QDomDocument>
#include <QFile>

#include <iostream> //debug
using std::cout;
using std::endl;

 //Helper Function (Code generation)
	#define getDomNodeValue(parent, name, sname, Name, func) \
		QDomNodeList dom##Name = dom##parent.item(0).toElement().elementsByTagName(QString(sname)); \
    if(dom##Name .size()) { \
			name = dom##Name.item(0).toElement().text()func; }

namespace Tubox {

Config::Config(const QString& filename) : filename(filename), port(0) { }

/**
 * <tubox>
 *   <user>User</user>
 *   <password>Pass</password>
 *   <serverUrl>http://...</serverUrl>
 *   <disk>/home/edokla/...</disk>
 *   <port>8080</port>
 * </tubox>
 */

bool Config::load() throw(XmlError) {
	QDomDocument xml(filename);
	QFile xmlFile(filename);
	xml.setContent(&xmlFile);
	QDomNodeList domConfig = xml.elementsByTagName("tubox");
	if(domConfig.size()) {
		getDomNodeValue(Config, user, "user", User,);
		getDomNodeValue(Config, password, "password", Password,);
		getDomNodeValue(Config, serverUrl, "serverUrl", ServerUrl,);
		getDomNodeValue(Config, disk, "disk", Disk,);
		getDomNodeValue(Config, port, "port", Port,.toInt());
		if(serverUrl.isEmpty() || disk.isEmpty() || user.isEmpty())
			return false;
		else
			return true;
	}
	throw XmlError("XML configuration error.", xml.toString());
	return false;
}

}

